<template>
  <div class="article-list">
    <div class="top">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题：">
          <el-input v-model="form.kw" style="width: 200px;margin-right: 20px" />
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="list">
      <el-table :data="list" border style="width: 100%">
        <el-table-column prop="articleId" label="文章ID" width="180" align="center" />
        <el-table-column prop="title" label="文章标题" />
        <el-table-column prop="author" label="作者" width="100" align="center" />
        <el-table-column prop="status" label="发布状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              class="ml-2"
              @change="publishArticle(scope.row)"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button size="small" type="success" @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除该文章吗？" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="bottom">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        v-model:page-size="size"
        :page-sizes="[10, 50, 100, 200]"
        class="mt-4"
      />
    </div>
  </div>
  
</template>

<script>
import { post, del, put } from '@/utils/request' 
function formatDate(millisecond, template) {
  var res = "";
  try {
    var date = new Date(millisecond);
    var opt = {
      "Y+": date.getFullYear().toString(), // 年
      "m+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "M+": date.getMinutes().toString(), // 分
      "S+": date.getSeconds().toString(), // 秒
    };
    template = template || "YYYY-mm-dd";
    for (var k in opt) {
      var ret = new RegExp("(" + k + ")").exec(template);
      if (ret) {
        template = template.replace(
          ret[1],
          ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
        );
      }
    }
    res = template;
  } catch (error) {
    console.warn("ERROR formatDate", error);
  }
  return res;
}
export default {
  name:'article-list',
  data() {
  return {
    list: [],
    form: {
      kw: ''
    },
    total: 0,
    currentPage: 1,
    size: 10
  }
  },
  methods: {
    // 获取文章数据
    getList() {
      let url = '/getAllArticles'
      const param = { size: this.size, page: this.currentPage }
      if (this.form.kw !== '') { // 存在搜索词需要调用查询接口
        param.kw = this.form.kw 
        url = '/getCurrentArticle'
      }
      post(url, param).then(res => {
        this.total = res.data.total
        this.list = res.data.data.map(item => {
          return {
            ...item,
            createTime: formatDate(item.createTime, 'YYYY-mm-dd HH:MM:SS'),
          }
        })
        console.log(this.list)
      })
    },
    // 搜索
    search() {
      this.currentPage = 1
      this.size = 10
      this.getList()
    },
    // 处理编辑按钮
    handleEdit(article) {
      this.$router.push({ path: '/addArticle', query: { id: article.articleId } })
    },
    // 处理删除按钮
    handleDelete(article) {
      del('/deleteArticle/' + article.articleId).then(res => {
        if (res.data === 1) {
          this.$message.success('删除文章成功')
          this.getList()
        }
      })
    },
    // 文章状态处理
    publishArticle(article) {
      put('/updateArticle', { articleId: article.articleId, status: article.status }).then(res => {
        if (res.data === 1) {
          if (article.status) {
            this.$message.success('文章发布成功')
          } else {
            this.$message.warning('文章已取消发布')
          }
        }
      })
    }
  },
  watch: {
    currentPage(val) {
      console.log('page', val)
      this.getList()
    },
    size(val) {
      console.log('size', val)
      this.getList()
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
.article-list {
  .top {
    padding: 20px 0;
    box-sizing: border-box;
    .title {
      display: inline-block;
    }
  }
  .bottom {
    margin-top: 20px;
  }
}
</style>
